package com.heny.demo.strategy;

import com.heny.demo.common.CommonErrorCode;
import com.heny.demo.common.CommonException;
import com.heny.demo.entity.TurnPointPOJO;
import com.opencsv.CSVReader;
import com.opencsv.exceptions.CsvException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author litao.cc
 * @version CsvProcessor.java v0.1 t2025/4/24 1:34
 * @date 2025/4/24 1:34
 * @description CsvProcessor
 */
public class CsvProcessor implements FileProcessorStrategy {

    private static final Logger logger = LoggerFactory.getLogger(CsvProcessor.class);

    @Override
    public List<TurnPointPOJO> processFile(MultipartFile file) {
        logger.info("CsvProcessor 开始处理文件：{0}", file.getName());
        List<TurnPointPOJO> result = new ArrayList<>();
        try {
            CSVReader reader = new CSVReader(new InputStreamReader(file.getInputStream()));
            List<String[]> allLines = null;
            allLines = reader.readAll();
            if (allLines.isEmpty()) return result;

            TurnPointPOJO row;
            for (int i = 0; i < allLines.size(); i++) {
                String[] values = allLines.get(i);
                row = FileProcessorStrategy.buildPOJO(values);
                if (row != null){
                    result.add(row);
                }
            }
        } catch (IOException | CsvException e) {
            logger.error("CsvProcessor 文件处理失败：{0}", e.getMessage());
            throw new CommonException(CommonErrorCode.FILE_SYS_ERROR, e.getMessage());
        }
        return result;
    }
}